import React, { useEffect, useRef } from 'react';
import type { Room } from '../../../types/room';
import { RoomStatus } from '../../../types/room';
import styles from '../styles/ContextMenu.module.css';

export interface ContextMenuAction {
  id: string;
  label: string;
  icon: string;
  disabled?: boolean;
  danger?: boolean;
  divider?: boolean;
  onClick: () => void;
}

interface ContextMenuProps {
  visible: boolean;
  x: number;
  y: number;
  room: Room | null;
  date: string | null;
  roomStatus?: RoomStatus;
  onClose: () => void;
  onAction: (actionId: string, room: Room, date: string) => void;
}

const ContextMenu: React.FC<ContextMenuProps> = ({
  visible,
  x,
  y,
  room,
  date,
  roomStatus,
  onClose,
  onAction,
}) => {
  const menuRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    if (visible) {
      document.addEventListener('mousedown', handleClickOutside);
      return () =>
        document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [visible, onClose]);

  // ESC键关闭菜单
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (visible) {
      document.addEventListener('keydown', handleKeyDown);
      return () => document.removeEventListener('keydown', handleKeyDown);
    }
  }, [visible, onClose]);

  if (!visible || !room || !date) return null;

  // 简化的菜单项 - 只保留核心功能
  const getMenuActions = (): ContextMenuAction[] => {
    const actions: ContextMenuAction[] = [];

    // 基础预订操作
    if (roomStatus === 'available') {
      actions.push({
        id: 'book',
        label: '新建预订',
        icon: '📅',
        onClick: () => handleAction('book'),
      });
    } else if (roomStatus === 'booked') {
      actions.push({
        id: 'checkin',
        label: '办理入住',
        icon: '🔑',
        onClick: () => handleAction('checkin'),
      });
      actions.push({
        id: 'modify',
        label: '修改预订',
        icon: '✏️',
        onClick: () => handleAction('modify'),
      });
      actions.push({
        id: 'cancel',
        label: '取消预订',
        icon: '❌',
        danger: true,
        onClick: () => handleAction('cancel'),
      });
    } else if (roomStatus === 'occupied') {
      actions.push({
        id: 'checkout',
        label: '办理退房',
        icon: '🚪',
        onClick: () => handleAction('checkout'),
      });
    }

    // 分割线
    if (actions.length > 0) {
      actions.push({
        id: 'divider1',
        label: '',
        icon: '',
        divider: true,
        onClick: () => {},
      });
    }

    // 房态管理 - 根据当前状态显示相应操作
    if (roomStatus === 'maintenance') {
      actions.push({
        id: 'available',
        label: '完成维护',
        icon: '✅',
        onClick: () => handleAction('available'),
      });
    } else if (roomStatus === 'cleaning' || roomStatus === 'cleaned') {
      actions.push({
        id: 'available',
        label: '清洁完成',
        icon: '✨',
        onClick: () => handleAction('available'),
      });
    } else if (roomStatus === 'checked_out') {
      actions.push({
        id: 'clean',
        label: '开始清洁',
        icon: '🧹',
        onClick: () => handleAction('clean'),
      });
    } else {
      // 可用状态或已预订状态可以设置维护
      actions.push({
        id: 'maintenance',
        label: '设为维护',
        icon: '🔧',
        onClick: () => handleAction('maintenance'),
      });

      if (roomStatus === 'available') {
        actions.push({
          id: 'clean',
          label: '开始清洁',
          icon: '🧹',
          onClick: () => handleAction('clean'),
        });
      }
    }

    // 合并相关操作
    actions.push({
      id: 'divider_merge',
      label: '',
      icon: '',
      divider: true,
      onClick: () => {},
    });

    actions.push({
      id: 'merge_suggest',
      label: '合并管理',
      icon: '🔗',
      onClick: () => handleAction('merge_suggest'),
    });

    if (roomStatus === 'booked' || roomStatus === 'occupied') {
      actions.push({
        id: 'merge_adjacent',
        label: '合并相邻预订',
        icon: '🧩',
        onClick: () => handleAction('merge_adjacent'),
      });
    }

    // 分割线
    actions.push({
      id: 'divider2',
      label: '',
      icon: '',
      divider: true,
      onClick: () => {},
    });

    // 基础信息
    actions.push({
      id: 'details',
      label: '房间详情',
      icon: 'ℹ️',
      onClick: () => handleAction('details'),
    });

    return actions;
  };

  const handleAction = (actionId: string) => {
    onAction(actionId, room, date);
    onClose();
  };

  const menuActions = getMenuActions();

  // 确保菜单不会超出屏幕边界
  const menuWidth = 250;
  const estimatedMenuHeight = Math.min(
    menuActions.length * 40 + 80, // 每项40px + 头部80px
    window.innerHeight - 20 // 留20px边距
  );

  let adjustedX = x;
  let adjustedY = y;

  // 水平位置调整
  if (x + menuWidth > window.innerWidth) {
    adjustedX = window.innerWidth - menuWidth - 10;
  }

  // 垂直位置调整
  if (y + estimatedMenuHeight > window.innerHeight) {
    adjustedY = window.innerHeight - estimatedMenuHeight - 10;
  }

  // 确保不超出左边界和上边界
  adjustedX = Math.max(10, adjustedX);
  adjustedY = Math.max(10, adjustedY);

  return (
    <div
      ref={menuRef}
      className={styles.contextMenu}
      style={{
        left: adjustedX,
        top: adjustedY,
      }}
    >
      <div className={styles.menuHeader}>
        <div className={styles.roomInfo}>
          <span className={styles.roomNumber}>{room.roomNumber}</span>
          <span className={styles.roomType}>{room.roomType}</span>
        </div>
        <div className={styles.dateInfo}>
          {new Date(date).toLocaleDateString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            weekday: 'short',
          })}
        </div>
      </div>

      <div className={styles.menuItems}>
        {menuActions.map(action => {
          if (action.divider) {
            return <div key={action.id} className={styles.divider} />;
          }

          return (
            <button
              key={action.id}
              className={`${styles.menuItem} ${
                action.danger ? styles.danger : ''
              } ${action.disabled ? styles.disabled : ''}`}
              onClick={action.onClick}
              disabled={action.disabled}
            >
              <span className={styles.icon}>{action.icon}</span>
              <span className={styles.label}>{action.label}</span>
            </button>
          );
        })}
      </div>

      <div className={styles.menuFooter}>
        <div className={styles.price}>¥{room.price}/晚</div>
        <div className={styles.building}>
          {room.building} {room.floor}楼
        </div>
      </div>
    </div>
  );
};

export default ContextMenu;
